<script setup lang="ts">
import { Refresh } from '@element-plus/icons-vue';
import {
useStatisticApplyCount,
useStatisticReport, useStatisticReportCount,
useStatisticReportExport
} from "@fl/api/elevator-api";
import { SubmitBtn } from "@fl/components";
import { Echart } from "@fl/origin-components/Echart";
import { cloneDeep } from "lodash-es";
import type { VxeGridProps } from "vxe-table";

const reportChartsCount = ref(0)
const applyChartsCount = ref(0)
const gridOptions = reactive<VxeGridProps>({
  border: true,
  columnConfig: {
    resizable: true,
  },
  columns: [
    { field: "areaName", title: "区（街道）" },
    { field: "communitiesCount", title: "具备加梯条件社区总数(个)" , sortable: true},
    { field: "joinCommunitiesCount", title: "申请社区数量(个)" , sortable: true},
    { field: "communitiesRate", title: "社区覆盖率(%)" , sortable: true},
    { field: "projectCount", title: "具备加梯条件小区总数(个)" , sortable: true},
    { field: "joinProjectCount", title: "申请小区数量(个)" , sortable: true},
    { field: "projectRate", title: "小区覆盖率(%)" , sortable: true},
  ],
  data: [],
  footerData:[],
  showFooter: true,
  showOverflow: true,
});
const reportCharts = ref({
  legend: {
    orient: "vertical",
    bottom: "3%", // 图例在底部
    left: "center", // 居中
    // height: 30,
    itemGap: 20, // 图例项之间的间距
    itemWidth: 10, // 图标宽度
    itemHeight: 10, // 图标高度
    icon: "circle", // 图标设置为圆形

    formatter: function (name) {
      const data = reportCountData?.value.find((item) => item.name === name);
      const total = reportCountData?.value.reduce((acc, cur) => acc + cur.value, 0);
      if (!data) {
        return name; // 如果找不到数据，则显示原始名称
      }
      const percentage =
        isFinite(total) && total !== 0
          ? ((data.value / total) * 100).toFixed(2) + "%"
          : "0.00%";

      return `{container|${data.name}} {middle|${data.value}}  {right|${percentage}}`;
    },
    textStyle: {
      rich: {
        container: {
          width:145,
          fontSize: 14,
          align: "left",
        },
        middle: {
          width:20,
          fontSize: 14,
          align: "right",

        },
        right: {
          width:60,
          fontSize: 14,
          align: "right",
        },
      },
    },
  },
  tooltip: {
    trigger: "item",
  },
  series: [
    {
      type: "pie",
      top: "-600",
      radius: ["40%", "70%"],
      tooltip: {
        trigger: "item",
      },
      data: [],
      label: {
        show: false,
        position: "center",
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: "bold",
          formatter: '{b} \n {d}%'
        
        },
      },
      labelLine: {
        show: false,
      },
    },
  ],
});
const applyCharts =ref({
  legend: {
    orient: "vertical",
    bottom: "3%", // 图例在底部
    left: "center", // 居中
    itemGap: 20, // 图例项之间的间距
    itemWidth: 10, // 图标宽度
    itemHeight: 10, // 图标高度
    icon: "circle", // 图标设置为圆形

    formatter: function (name) {
      const data = applyCountData?.value.find((item) => item.name === name);
      const total = applyCountData?.value.reduce((acc, cur) => acc + cur.value, 0);
      if (!data) {
        return name; // 如果找不到数据，则显示原始名称
      }
      const percentage =
        isFinite(total) && total !== 0
          ? ((data.value / total) * 100).toFixed(2) + "%"
          : "0.00%";

      return `{container|${data.name}} {middle|${data.value}}  {right|${percentage}}`;
    },
    textStyle: {
      rich: {
        container: {
          width:145,
          fontSize: 14,
          align: "left",
        },
        middle: {
          width:20,
          fontSize: 14,
          align: "right",

        },
        right: {
          width:60,
          fontSize: 14,
          align: "right",
        },
      },
    },
  },
  tooltip: {
    trigger: "item",
  },
  series: [
    {
      type: "pie",
      top: "-600",
      radius: ["40%", "70%"],
      tooltip: {
        trigger: "item",
      },
      data: [],
      label: {
        show: false,
        position: "center",
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: "bold",
          formatter: '{b} \n {d}%'
        
        },
      },
      labelLine: {
        show: false,
      },
    },
  ],
});
const { data, isLoading,refetch:reportReftch } = useStatisticReport(); //各区（街道）需求上报
const {
  data: reportCountData,
  isLoading: reportCountLoading
} = useStatisticReportCount();
const { data: applyCountData, isLoading: applyCountLoading } = useStatisticApplyCount();
const {
  isPending: exportReportPending,
  mutateAsync: exportReportMutate,
} = useStatisticReportExport();
async function exportReport() {
  const res = await exportReportMutate();
  if (res) {
    const objectUrl = URL.createObjectURL(res);
    location.href = objectUrl;
    URL.revokeObjectURL(objectUrl);
  }
}
watchEffect(() => {
    if (data.value) {
    gridOptions.data = cloneDeep(data.value.slice(0, -1));
    gridOptions.footerData  = cloneDeep(data.value.slice(-1));
  }
  if (reportCountData.value) {
    reportCharts.value.series[0].data = cloneDeep(reportCountData.value);
    reportChartsCount.value =  reportCountData.value.reduce((a, b) => {
      return a + b.value;
    }, 0);
  }
  if(applyCountData.value){
    applyCharts.value.series[0].data = cloneDeep(applyCountData.value);
    applyChartsCount.value = applyCountData.value.reduce((a, b) => {
      return a + b.value;
    }, 0);
  }
})
</script>
<template>

<ElRow :gutter="16" justify="space-between" class="mb20">
    <ElCol :xl="12" :lg="12" :md="12" :sm="12" :xs="12">
      <ElCard shadow="hover" style="height: 1000px !important;">
        <div class="font-550 mb20 text-18 flex items-center justify-between">
          <div>各区（街道）需求上报情况-申请社区及申请小区覆盖率</div>
          <div class="flex items-center">
          <div class="color-[#235FC4] flex items-center font-400 mr20 cursor-pointer">
            <el-button :icon="Refresh"  @click="reportReftch">刷新</el-button>
          </div>
          <SubmitBtn @click="exportReport" :isLoading="exportReportPending" type="primary"
            >导出</SubmitBtn>
          </div>
         
        </div>
        <vxe-grid
          ref="xGrid"
          v-bind="gridOptions"
          align="center"
          class="mb12"
          :loading="isLoading"
        >
        </vxe-grid>
      </ElCard>
    </ElCol>
    <ElCol :xl="6" :lg="6" :md="6" :sm="6" :xs="6">
      <ElCard shadow="hover" style="height: 1000px !important;">
        <div class="font-550 mb20 text-18">各区（街道）需求上报情况——申请占比</div>
        <ElSkeleton :loading="reportCountLoading" animated>
        <div>总计：{{ reportChartsCount }}台
        </div>
          <Echart id="reportCount" :options="reportCharts" :height="900" />
        </ElSkeleton>
      </ElCard>
    </ElCol>

    <ElCol :xl="6" :lg="6" :md="6" :sm="6" :xs="6">
      <ElCard shadow="hover" style="height: 1000px !important;">
        <div class="font-550 mb20 text-18">各区（街道）完成业主意见征询占比</div>
        <ElSkeleton :loading="applyCountLoading" animated>
          <div>总计：{{ applyChartsCount }}台</div>

          <Echart id="applyCount" :options="applyCharts" :height="900" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
  </ElRow>
</template>